/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

import buildURL from '../../node_modules/axios/lib/helpers/buildURL'
import buildFullPath from '../../node_modules/axios/lib/core/buildFullPath'
import settle from "../../node_modules/axios/lib/core/settle"
import AxiosError from '../../node_modules/axios/lib/core/AxiosError'
import http from '@ohos.net.http'

export default (config, resolve, reject)=>{
    let requestData = config.data;
    let fullPath = buildFullPath(config.baseURL, config.url);

    // 每一个httpRequest对应一个http请求任务，不可复用
    let httpRequest = http.createHttp();

    let options = {
        method: config.method.toUpperCase(),
        header: config.headers, // 开发者根据自身业务需要添加header字段
    }
    if(requestData){ // 当使用POST请求时此字段用于传递内容
        options.extraData = requestData
    }
    if(config.timeout && typeof(config.timeout) === 'number'){
        options.readTimeout = config.timeout
    }
    if(!fullPath){
        reject(new AxiosError("Cannot read properties of url!", AxiosError.ERR_BAD_OPTION, config, httpRequest, httpRequest));
        return
    }else if(typeof(fullPath) !== 'string'){
        reject(new AxiosError("Url type should be character type！", AxiosError.ERR_BAD_OPTION, config, httpRequest, httpRequest));
        return
    }
    httpRequest.request(
        // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
        buildURL(fullPath, config.params, config.paramsSerializer), options
            , (err, data) => {
            if(!err) {
                let response = {
                    data: data && data.result,
                    status: data && data.responseCode,
                    statusText: "",
                    headers: data && data.header,
                    config: config,
                    request: httpRequest
                };
                settle(function _resolve(value) {
                    resolve(value);
                }, function _reject(err) {
                    reject(err);
                }, response);
            }else{
                // 无网络或者url错误
                reject(new AxiosError(JSON.stringify(err), err.code, config, httpRequest, httpRequest));
            }
            httpRequest.destroy();
        });
}



